package textapp.business;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.google.gson.Gson;

import textapp.connector.push.PushMessage;
import textapp.dao.MessageDao;
import textapp.dao.UserDao;
import textapp.dao.model.Message;
import textapp.dao.model.User;

public class MessageService {
	
	public static final boolean PUSH_MESSAGE = true;
	
	public static void main(String[] args) {
		//new MessageService().saveMessage("1fasfaf", 2, 1, 0, 0);
		//new MessageService().updateMessageStatus(1, 1);
		List<Message> ms = new MessageService().getConversationByTime(2, 1, 0);
		System.out.println(ms.size());
		
	}
	
	public Message saveMessage(String text, int toUserId, int fromUserId, int type, int lifetimeMin) {
		UserDao uDao = new UserDao();
		User to = uDao.findById(toUserId);
		User from = uDao.findById(fromUserId);
		if (to == null || from == null) {
			System.out.println("TO: "+to+"FROM:"+from);
			return null;
		}
		Message message = new Message();
		Date now = new Date();
		message.setTo(to);
		message.setFrom(from);
		message.setText(text);
		message.setType(type);
		message.setStatus(0);
		message.setCreateDate(now);
		message.setModifyDate(now);
		message.setLifetimeMin(lifetimeMin);
		message = new MessageDao().create(message);
		
		if (PUSH_MESSAGE && PushMessageService.isPushAble(to)) {
			PushMessageService service = new PushMessageService();
			PushMessage pm = new PushMessage();			
			StringBuilder str = new StringBuilder(MessageUtil.cutStr(from.getName(), 6, true));
			str.append(":");
			str.append(MessageUtil.cutStr(message.getText(), 15, true));
			pm.setText(str.toString());
			pm.setType(PushMessage.PUSH_TYPE_NORMAL_MESSAGE);
			try {
				boolean result = service.sendPushMessage(to.getPushIdentity(), String.valueOf("U"+to.getId()), pm, false);				
			} catch (IOException e) {
				
			}
		}
		
		return message;
	}
	
	public boolean updateMessageStatus(int messageId, int status) {
		return new MessageDao().updateStatus(messageId, status);
	}
	
	public List<Message> getMessages(int userId, long beginTimeStampMS) {
		return new MessageDao().getMessagesByUserIdAndTime(userId, beginTimeStampMS);
	}
	
//	public List<Message> getMessages(int userId, long beginTimeStampMS) {
//		return new MessageDao().getMessagesByUserIdAndTime(userId, beginTimeStampMS);
//	}
	
	public List<Message> getConversationByTime(int toUserId, int fromUserId, long beginTimeStampMS) {
		return new MessageDao().getConversationByTime(toUserId, fromUserId, beginTimeStampMS);
	}
	
	
}
